package com.ctshk.rpc.goods.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.GlobalConstants;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.goods.dto.ShoppingShopDTO;
import com.ctshk.rpc.goods.entity.ShoppingShop;
import com.ctshk.rpc.goods.entity.ShoppingShopKeyWord;
import com.ctshk.rpc.goods.entity.ShoppingSpecial;
import com.ctshk.rpc.goods.mapper.ShoppingShopKeyWordMapper;
import com.ctshk.rpc.goods.mapper.ShoppingShopMapper;
import com.ctshk.rpc.goods.mapper.ShoppingSpecialMapper;
import com.ctshk.rpc.goods.req.ShoppingShopAddReq;
import com.ctshk.rpc.goods.req.ShoppingShopKeyWordAddReq;
import com.ctshk.rpc.goods.req.ShoppingShopPageReq;
import com.ctshk.rpc.goods.req.ShoppingShopUpdateStatusReq;
import com.ctshk.rpc.goods.service.IShoppingShopService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysPermissionService;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商城管理 服务实现类
 * </p>
 *
 * @author 姜斌文
 * @since 2021-04-06
 */
@DubboService
public class ShoppingShopServiceImpl extends ServiceImpl<ShoppingShopMapper, ShoppingShop> implements IShoppingShopService {

    @Autowired
    private ShoppingShopMapper shoppingShopMapper;
    @Autowired
    private ShoppingShopKeyWordMapper shopKeyWordMapper;
    @Autowired
    private ShoppingSpecialMapper shoppingSpecialMapper;
    @DubboReference
    private ISysPermissionService sysPermissionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addShoppingShop(ShoppingShopAddReq shopAddReq, Long userId) {
        ShoppingShop shop = new ShoppingShop();
        BeanUtils.copyProperties(shopAddReq, shop);
        LocalDateTime now = LocalDateTime.now();
        Long id = SnowflakeIdWorker.nextId();
        shop.setId(id);
        shop.setCreateId(userId);
        shop.setGmtCreate(now);
        shop.setModifiedId(userId);
        shop.setGmtModified(now);
        shop.setIsDeleted(IsDeletedCode.NO.getCode());
        shop.setStatus(1);
        shop.setShopUrl("https://m.ctshk.com/"+id);
        shoppingShopMapper.insert(shop);
        // 新增关键词对象
        ShoppingShopKeyWordAddReq keyWordAddReq = shopAddReq.getKeyWordAddReq();
        if(keyWordAddReq != null){
            ShoppingShopKeyWord shoppingShopKeyWord = new ShoppingShopKeyWord();
            BeanUtils.copyProperties(keyWordAddReq, shoppingShopKeyWord);
            shoppingShopKeyWord.setId(SnowflakeIdWorker.nextId());
            shoppingShopKeyWord.setShopId(shop.getId());
            shoppingShopKeyWord.setCreateId(userId);
            shoppingShopKeyWord.setModifiedId(userId);
            shoppingShopKeyWord.setIsDeleted(0);
            shopKeyWordMapper.insert(shoppingShopKeyWord);
        }
        LocalDateTime nowLocalDateTime = LocalDateTime.now();
        // 创建四个专题
        for (int i = 0; i < 4; i++) {
            ShoppingSpecial shoppingSpecial = new ShoppingSpecial();
            shoppingSpecial.setShoppingShopId(shop.getId());
            shoppingSpecial.setOperatorId(String.valueOf(shop.getOperatorId()));
            shoppingSpecial.setIsDeleted(0);
            shoppingSpecial.setCreateId(shop.getCreateId());
            shoppingSpecial.setModifiedId(shop.getModifiedId());
            shoppingSpecial.setId(SnowflakeIdWorker.nextId());
            // 默认名称 1~4
            shoppingSpecial.setSpecialTitle(String.valueOf((i + 1)));
            shoppingSpecial.setGmtCreate(nowLocalDateTime);
            shoppingSpecial.setGmtModified(nowLocalDateTime);
            shoppingSpecialMapper.insert(shoppingSpecial);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateShoppingShop(ShoppingShopAddReq shopAddReq, Long userId) {
        ShoppingShop shop = shoppingShopMapper.selectById(shopAddReq.getId());
        BeanUtils.copyProperties(shopAddReq, shop, EntityUtil.getNullPropertyNames(shopAddReq));
        LocalDateTime now = LocalDateTime.now();
        shop.setModifiedId(userId);
        shop.setGmtModified(now);
        shoppingShopMapper.updateById(shop);
        ShoppingShopKeyWordAddReq shopKeyWordAddReq = shopAddReq.getKeyWordAddReq();
        if (null != shopKeyWordAddReq && shopKeyWordAddReq.getWords().length() > 0) {
            List<String> wordList = Arrays.asList(shopKeyWordAddReq.getWords().split(","));
            List<ShoppingShopKeyWord> shopKeyWordList = new ArrayList<ShoppingShopKeyWord>();
            wordList.forEach(wordStr -> {
                ShoppingShopKeyWord shopKeyWord = new ShoppingShopKeyWord();
                shopKeyWord.setShopId(shop.getId());
                shopKeyWord.setWords(wordStr);
                shopKeyWord.setType(shop.getShopType());
                shopKeyWord.setCreateId(shop.getCreateId());
                shopKeyWord.setGmtCreate(shop.getGmtCreate());
                shopKeyWord.setModifiedId(userId);
                shopKeyWord.setGmtModified(now);
                shopKeyWord.setIsDeleted(IsDeletedCode.NO.getCode());
                shopKeyWordList.add(shopKeyWord);
            });
            if (null != shopKeyWordList && shopKeyWordList.size() > 0) {
                List<ShoppingShopKeyWord> keyWordIds = shopKeyWordMapper.selectChildren(shopAddReq.getId());
                if (null != keyWordIds && keyWordIds.size() > 0) {
                    List<Long> delIds = keyWordIds.stream().map(ShoppingShopKeyWord::getId).collect(Collectors.toList());
                    shopKeyWordMapper.deleteBatchIds(delIds);
                }
                shopKeyWordMapper.insertBatchSomeColumn(shopKeyWordList);
            }
        }
    }

    @Override
    public void updateShoppingShopStatus(ShoppingShopUpdateStatusReq shopUpdateReq, Long userId) {
        if (null != shopUpdateReq && null != shopUpdateReq.getId() && null != shopUpdateReq.getStatus()) {
            ShoppingShop shop = shoppingShopMapper.selectById(shopUpdateReq.getId());
            BeanUtils.copyProperties(shopUpdateReq, shop, EntityUtil.getNullPropertyNames(shopUpdateReq));
            LocalDateTime now = LocalDateTime.now();
            shop.setModifiedId(userId);
            shop.setGmtModified(now);
            shoppingShopMapper.updateById(shop);
        }
    }

    @DubboReference
    private ISysUserService sysUserService;

    @Override
    public PageResponse<ShoppingShopDTO> findShoppingShopByAll(ShoppingShopPageReq pageReq, TokenUser tokenUser) {
        Result<List<Long>> permissionResult = sysPermissionService.queryPermission(pageReq.getMenuId(), tokenUser.getId());
        if (!permissionResult.isSuccess()) {
            SystemError result = SystemError.getDefined(permissionResult.getCode());
            throw new BusinessException(result);
        }
        //不是管理员
        if (!GlobalConstants.Role.isAdmin(tokenUser.getUsername())) {
            pageReq.setIsNotAdmin(1);
            String ids = "";
            List<Long> data = permissionResult.getData();
            if(data != null && data.size() >0){
                for (Long datum : data) {
                    ids += datum + ",";
                }
            }
            if(ids.length() > 0){
                ids = ids.substring(0, ids.length() - 1);
            }
            pageReq.setUserIds(ids);
        }

        IPage<ShoppingShopDTO> page = new Page<ShoppingShopDTO>(pageReq.getPageNo(), pageReq.getPageSize());
        IPage<ShoppingShopDTO> iPage = shoppingShopMapper.findShoppingShopByAll(page, pageReq);
        List<ShoppingShopDTO> shoppingShopList = new ArrayList<>();
        for (ShoppingShopDTO shoppingShopDTO : iPage.getRecords()) {
            if (null != shoppingShopDTO.getOperatorId()) {
                UserDTO userDTO = sysUserService.queryCacheUser(shoppingShopDTO.getOperatorId());
                shoppingShopDTO.setOperationName(userDTO.getFullName() + "/" + userDTO.getDept());
            }
            shoppingShopList.add(shoppingShopDTO);
        }
        List<ShoppingShopDTO> pageDTOList = EntityUtil.copyList(shoppingShopList, ShoppingShopDTO.class);

        return new PageResponse<>(pageDTOList, iPage.getCurrent() == 1,
                iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
                iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }

    @Override
    public List<ShoppingShopDTO> findShoppingShopNameList(Long menuId, TokenUser tokenUser) {
        String ids = "";
        Result<List<Long>> permissionResult = sysPermissionService.queryPermission(menuId, tokenUser.getId());
        if (!permissionResult.isSuccess()) {
            SystemError result = SystemError.getDefined(permissionResult.getCode());
            throw new BusinessException(result);
        }
        //不是管理员
        if (!GlobalConstants.Role.isAdmin(tokenUser.getUsername())) {
            List<Long> data = permissionResult.getData();
            if(data != null && data.size() >0){
                for (Long datum : data) {
                    ids += datum + ",";
                }
            }
            if(ids.length() > 0){
                ids = ids.substring(0, ids.length() - 1);
            }
        }

        return shoppingShopMapper.findShoppingShopNameList(ids);
    }

    @Override
    public ShoppingShopDTO findShoppingShopInfoById(Long id) {
        ShoppingShopDTO shoppingShopDTO = shoppingShopMapper.findShoppingShopInfoById(id);
        List<ShoppingShopKeyWord> shoppingShopKeyWords = shopKeyWordMapper.findShoppingShopKeyWordsListByShopId(id);

        if (shoppingShopKeyWords != null && shoppingShopKeyWords.size() > 0) {
            String words = "";
            for (ShoppingShopKeyWord shoppingShopKeyWord : shoppingShopKeyWords) {
                words += shoppingShopKeyWord.getWords() + ",";
            }
            if (words.endsWith(",")) {
                words = words.substring(0, words.length() - 1);
            }
            if (shoppingShopDTO != null) {
                shoppingShopDTO.setWords(words);
            }
        }
        return shoppingShopDTO;
    }
}
